package com.rednote.service;

import com.rednote.entity.UserPostRating;
import com.rednote.mapper.UserPostRatingMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class RatingService {
    private final UserPostRatingMapper ratingMapper;

    // 行为权重配置（可存数据库）
    private static final Map<String, Integer> BEHAVIOR_WEIGHTS = Map.of(
            "LIKE", 5,
            "FAVORITE", 4,
            "VIEW", 1,
            "COMMENT", 3
    );

    @Transactional
    public void updateUserPostRating(long userId, long postId, String behavior) {
        Integer weight = BEHAVIOR_WEIGHTS.getOrDefault(behavior, 0);
        if (weight == 0) return;

        UserPostRating existing = ratingMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserPostRating>()
                .eq("user_id", userId)
                .eq("post_id", postId)
        );
        if (existing == null) {
            // 新建
            UserPostRating upr = new UserPostRating(userId, postId, weight);
            ratingMapper.insert(upr);
        } else {
            // 叠加
            existing.setValue(existing.getValue() + weight);
            ratingMapper.updateById(existing);
        }
    }
}
